##########################################################################
# This is a class to implement the CRC_CCITT 0x1D0F checksum
##########################################################################
import time
import serial

global ser

class CRC_CCITT:
   def __init__(self):
      self.tab=256*[[]]
      for i in xrange(256):
         crc=0
         c = i << 8

         for j in xrange(8):
            if (crc ^ c) & 0x8000:
               crc = ( crc << 1) ^ 0x1021
            else:
                  crc = crc << 1
            c = c << 1
            crc = crc & 0xffff
         self.tab[i]=crc
   
   def update_crc(self, crc, c):
      short_c=0x00ff & (c % 256)
      tmp = ((crc >> 8) ^ short_c) & 0xffff
      crc = (((crc << 8) ^ self.tab[tmp])) & 0xffff
      return crc 

def initComm(serialnum):
    global ser
    try:
        ser = serial.Serial(serialnum-1,57600)
        return ("success")
    except:
        print "Couldnt open"
        return ("failed")


def addCRCandSend(sendstring):
    global ser

    #Calculate Checksum
    Checksum=CRC_CCITT()
    crcval=0x1D0F  #initialize for CCITT 0x1DOF
    for c in sendstring:
        crcval=Checksum.update_crc(crcval, ord(c))
    sendstring = "[" + sendstring + "%0.4X"%crcval + "]"

    #print sendstring

    try:
        ser.write(sendstring+chr(13))
        return ("success")
    except:
        return ("failure")

def readDATA():
    global ser
    try:
        line = ser.readline()
    except:
        line = "failure: Check Comms"
    return line